package activity.luntan;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.login.ActivityLogin;
import adapter.HuiFuAdapter;
import base.MyApplcation;
import bean.HuiFuBean;
import bean.TopicDetailBean;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import presenter.LunTanPresenter;
import util.BaseOtherActivity;
import util.GlideLoader;
import util.MyListView;
import util.XScrollView;
import util.utls.BasePtr;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.MyGongJv;
import util.utls.SPUtils;
import util.volley.ResultEntity;
import widget.InputMethodLayout;
import widget.chatemoji.FaceInputView;
import widget.chatemoji.Spanned2String;
import widget.grid.NineGridTestLayout;

/**
 * 帖子详情
 */
public class ToPicDetailActivity extends BaseOtherActivity implements Observer,HuiFuAdapter.ClickListener{
    PtrFrameLayout commend_anchor_ptr;
    XScrollView home_scrollView;
    ImageView back;
    TextView tvTitle;
    LunTanPresenter lunTanPresenter;
    NineGridTestLayout layout_nine_grid;
    TextView txt_title, txt_time, txt_author, txt_content;
    TextView zhuanfa_tv, pinglun_tv, zan_tv;
    ImageView img_head;

    LinearLayout li_bottom,li_bottoms;
    EditText ed_content;
    TextView fasong;
    ToggleButton toggle_pinglun;
    private TopicDetailBean model;
    MyListView list_pinglun;
    int id;
    String uid;

    HuiFuBean huiFuBean;
    List<HuiFuBean.TopicList> beanList;
    int size = 1;
    int page = 10;

    HuiFuAdapter adapter;

    InputMethodLayout root_pinglun;
    String pinglun = "0";//限制回复

    RelativeLayout li_bottoms_ping;

    int type=1;//来标记是回复还是转发   1 转发    2 回复   3回复下级列表

    int pinglunPosition;//评论的是哪一条

    private Dialog dialog;// 自定义Dialog
    int deleteRid;

    ImageView emoji;//表情按钮

    LinearLayout faceInputContainer;//表情显示布局
    private FaceInputView faceInputView;//表情
    @Override
    protected int layout_id() {
        return R.layout.activity_to_pic_detail;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {
        read();
        tvTitle.setText("话题");
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);
        huiFuBean = new HuiFuBean();
        beanList = new ArrayList<>();
        lunTanPresenter = new LunTanPresenter(this);
        id = getIntent().getIntExtra("id", 0);
        uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
        showExtraDialog();
        showProgressDialog("正在加载数据...", true);
        lunTanPresenter.topicDetail(id, uid);
        lunTanPresenter.topicHuiFuList(uid, id + "", "", size, page);
        adapter = new HuiFuAdapter(ToPicDetailActivity.this, beanList,this);
        list_pinglun.setAdapter(adapter);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                size++;
                lunTanPresenter.topicHuiFuList(uid, id + "", "", size, page);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                lunTanPresenter.topicHuiFuList(uid, id + "", "", size, page);
            }
        });
        commend_anchor_ptr.autoRefresh(true);
        biaoqing();
    }
    private void biaoqing(){
        faceInputView = new FaceInputView(this);
        faceInputContainer.addView(faceInputView);
        faceInputView.setOnClickListener(new FaceInputListenr());
    }
    private class FaceInputListenr implements FaceInputView.OnFaceClickListener {

        @Override
        public void selectedFace(FaceInputView.Face face) {
            int id = face.faceId;
            if (id == R.drawable.ic_face_delete_normal)// 删除按钮
            {
                int index = ed_content.getSelectionStart();
                if (index == 0)
                    return;
                Editable editable = ed_content.getText();
                editable.delete(index - 1, index);// 删除最后一个字符或表情
            } else {
                ed_content.append(Html.fromHtml("<img src='" + id + "'/>",
                        imageGetter, null));// 添加表情
            }
        }

    }

    // 输入表情需要
    Html.ImageGetter imageGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
            int id = Integer.parseInt(source);
            @SuppressWarnings("deprecation")
            Drawable d = getResources().getDrawable(id);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        lunTanPresenter.topicHuiFuList(uid, id + "", "", size, page);
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }
    /**
     * 操作一些数据
     */
    private void read() {
        root_pinglun = (InputMethodLayout) findViewById(R.id.root_pinglun);
        root_pinglun.setOnkeyboarddStateListener(new InputMethodLayout.onKeyboardsChangeListener() {// 监听软键盘状态
            @Override
            public void onKeyBoardStateChange(int state) {
                // TODO Auto-generated method stub
                switch (state) {
                    case InputMethodLayout.KEYBOARD_STATE_SHOW:
                        if (faceInputContainer.getVisibility()!= View.VISIBLE){
                            li_bottoms.setVisibility(View.VISIBLE);
                        }

                        //  Toast.makeText(ToPicDetailActivity.this, "打开软键盘", 1000).show();
                        break;
                    case InputMethodLayout.KEYBOARD_STATE_HIDE:
                        //  Toast.makeText(ToPicDetailActivity.this, "关闭软键盘", 1000).show();
                        if (faceInputContainer.getVisibility()!= View.VISIBLE){
                            li_bottoms.setVisibility(View.GONE);
                            ed_content.setText("");
                        }
                        break;
                }
            }
        });
        //评论的ToggleButton点击
        toggle_pinglun.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    pinglun = "1";
                } else {
                    pinglun = "0";
                }
            }
        });
        list_pinglun.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (uid.equals(String.valueOf(beanList.get(position).getUid()))){
                    deleteRid= beanList.get(position).getId();
                    dialog.show();
                }
            }
        });

        txt_content.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipboardManager cm =(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(Spanned2String.parse(model.getContent()));
                ByAlert.alert("复制成功");
                return true;
            }
        });
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
    }

    @Override
    public void update(Observable observable, Object data) {
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == LunTanPresenter.topicDetail_success) {
                model = (TopicDetailBean) entity.getData();
                setData();

            } else if (entity.getEventType() == LunTanPresenter.topicDetail_success) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == LunTanPresenter.huifu_success) {  //帖子回复列表
                if (size == 1) {
                    beanList.clear();
                }
                commend_anchor_ptr.refreshComplete();
                huiFuBean = (HuiFuBean) entity.getData();
                if (huiFuBean != null) {
                    beanList.addAll(huiFuBean.getList());
                    adapter.notifyDataSetChanged();
                }

            } else if (entity.getEventType() == LunTanPresenter.huifu_success) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == LunTanPresenter.zan_success) {  //帖子点赞
                ByAlert.alert(entity.getData());

                zan_tv.setText(Integer.parseInt(model.getLikes()) + 1 + "");

            } else if (entity.getEventType() == LunTanPresenter.zan_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == LunTanPresenter.zhuanfa_tiezi_success) {//帖子转发
                ByAlert.alert(entity.getData());

                lunTanPresenter.topicDetail(id, uid);

            } else if (entity.getEventType() == LunTanPresenter.zhuanfa_tiezi_fail) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == LunTanPresenter.huifu_tiezi_success) {//帖子回复
                ByAlert.alert(entity.getData());
                lunTanPresenter.topicHuiFuList(uid, id + "", "", size, page);
                adapter.notifyDataSetChanged();

                lunTanPresenter.topicDetail(id, uid);

            } else if (entity.getEventType() == LunTanPresenter.huifu_tiezi_fail) {
                ByAlert.alert(entity.getData());
            }
            else if (entity.getEventType() == LunTanPresenter.delete_pinglun_success) {//删除自己的评论
                lunTanPresenter.topicDetail(id, uid);
                Iterator<HuiFuBean.TopicList> iterator=beanList.iterator();
                while (iterator.hasNext()){
                    HuiFuBean.TopicList lists=iterator.next();
                    if (lists.getId()==deleteRid){
                        iterator.remove();
                        adapter.notifyDataSetChanged();
                        break;
                    }
                }
            }
            else if (entity.getEventType() == LunTanPresenter.delete_pinglun_fail) {
                ByAlert.alert(entity.getData());
            }
        }
    }

    private void setReply() {
        //显示评论及回复.待实现
//        list_pinglun.setAdapter();
    }

    private void setData() {
        zhuanfa_tv.setText(model.getRepeat_count());
        pinglun_tv.setText(model.getReplys_direct_count());
        zan_tv.setText(model.getLikes());

        txt_title.setText(model.getTitle());
        txt_content.setText(model.getContent());
        txt_time.setText(model.getCreate_time_desc());
        txt_author.setText(model.getUname());
        layout_nine_grid.setUrlList(model.getImg());
       // XImageLoader.load(Const.IMAGE_HEAD_TWO + model.getUid(), img_head);
        GlideLoader.displayImageHeadCircular(model.getUid(),img_head);
        setReply();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.emoji:
                if (faceInputContainer.getVisibility()== View.VISIBLE){
                    faceInputContainer.setVisibility(View.GONE);
                    emoji.setBackgroundResource(R.drawable.emoji);
                }else{
                    faceInputContainer.setVisibility(View.VISIBLE);
                    emoji.setBackgroundResource(R.drawable.jianpan);
                }
                MyGongJv.yincang(v);
                break;
            case R.id.ed_content:
                if (faceInputContainer.getVisibility()== View.VISIBLE){
                    faceInputContainer.setVisibility(View.GONE);
                    emoji.setBackgroundResource(R.drawable.emoji);
                }
                break;
            case R.id.back:
                finish();
                break;
            case R.id.zhuanfa_tv://转发n
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(ToPicDetailActivity.this, ActivityLogin.class);
                    startActivity(intent1);
                    return;
                }
                type=1;
                ed_content.setHint("请输入转发理由");

                li_bottoms.setVisibility(View.VISIBLE);
                li_bottoms_ping.setVisibility(View.VISIBLE);
                MyGongJv.xianshi();
                ed_content.requestFocus();
                break;
            case R.id.pinglun_tv://评论
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(ToPicDetailActivity.this, ActivityLogin.class);
                    startActivity(intent1);
                    return;
                }
                type=2;
                ed_content.setHint("回复评论");

                li_bottoms.setVisibility(View.VISIBLE);
                li_bottoms_ping.setVisibility(View.INVISIBLE);
                MyGongJv.xianshi();
                ed_content.requestFocus();
                break;
            case R.id.zan_tv://赞
                if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
                    Intent intent1 = new Intent(ToPicDetailActivity.this, ActivityLogin.class);
                    startActivity(intent1);
                    return;
                }
                lunTanPresenter.dianzan(uid, model.getId() + "", "");
                break;
            case R.id.fasong://转发说说
                faceInputContainer.setVisibility(View.GONE);
                String content = ed_content.getText().toString().trim();
                if (type==1){
                    if (content.equals("")) {
                        ByAlert.alert("请输入转发理由");
                        return;
                    }
                    showProgressDialog("正在转发,请稍后...", true);
                    MyGongJv.yincang(v);
                    lunTanPresenter.zhuanfaTieZi(uid, Spanned2String.parse(ed_content.getText()), pinglun, model.getId() + "", Const.APP_FOR);
                }else if (type==2){
                    if (content.equals("")) {
                        ByAlert.alert("请输入回复内容");
                        return;
                    }
                    showProgressDialog("正在发表,请稍后...", true);
                    MyGongJv.yincang(v);
                    lunTanPresenter.huifuTieZi(uid,model.getId() + "", "","",Spanned2String.parse(ed_content.getText()),"", Const.APP_FOR);
                }else{
                    if (content.equals("")) {
                        ByAlert.alert("请输入回复内容");
                        return;
                    }
                    showProgressDialog("正在发表,请稍后...", true);
                    MyGongJv.yincang(v);
                    lunTanPresenter.huifuTieZi(uid,model.getId() + "", beanList.get(pinglunPosition).getId()+"",beanList.get(pinglunPosition).getTo_uid()+"",Spanned2String.parse(ed_content.getText()),"", Const.APP_FOR);
                }
                li_bottoms.setVisibility(View.GONE);
                ed_content.setText("");
                break;

        }
    }
    //每条评论的回复
    @Override
    public void pinglun(View v) {
        if (IsUtilUid.isUid() == null || IsUtilUid.isUid() == "") {
            Intent intent1 = new Intent(ToPicDetailActivity.this, ActivityLogin.class);
            startActivity(intent1);
            return;
        }
        pinglunPosition = (Integer) v.getTag();
        type=3;
        ed_content.setHint("回复:"+beanList.get(pinglunPosition).getUname());
        li_bottoms_ping.setVisibility(View.INVISIBLE);
        MyGongJv.xianshi();
        ed_content.requestFocus();
    }

    /**
     * 删除Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(this, R.style.rel_dialog);
        View view = LayoutInflater.from(this).inflate(
                R.layout.dialog_delete, null);
        dialog.setContentView(view);

        TextView dialog_ok = (TextView) view.findViewById(R.id.dialog_ok);
        TextView dialog_quxiao = (TextView) view.findViewById(R.id.dialog_quxiao);
        TextView user_title = (TextView) view.findViewById(R.id.user_title);
        TextView dialog_conext = (TextView) view.findViewById(R.id.dialog_conext);
        user_title.setText("删除回复");
        dialog_conext.setText("确定删除此回复？");

        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
                showProgressDialog("刪除中,请稍后...",false);
                lunTanPresenter.deleteMyHuiFu(uid,deleteRid);
            }
        });
        dialog_quxiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }
}
